 
#include"glad/glad.h"
#include"OpenGLVertexArray.h"
//#include"mgepch.h"


namespace myMiniEngine {

	static GLenum ShaderDataTypeToGLBaseType(ShaderDataType type) {
		switch (type)
		{
		case myMiniEngine::ShaderDataType::Float:   return GL_FLOAT;
		case myMiniEngine::ShaderDataType::Float2:  return GL_FLOAT;
		case myMiniEngine::ShaderDataType::Float3:  return GL_FLOAT;
		case myMiniEngine::ShaderDataType::Float4:  return GL_FLOAT;
		case myMiniEngine::ShaderDataType::Mat3:    return GL_FLOAT;
		case myMiniEngine::ShaderDataType::Mat4:    return GL_FLOAT;
		case myMiniEngine::ShaderDataType::Int:     return GL_INT;
		case myMiniEngine::ShaderDataType::Int2:    return GL_INT;
		case myMiniEngine::ShaderDataType::Int3:    return GL_INT;
		case myMiniEngine::ShaderDataType::Int4:    return GL_INT;
		case myMiniEngine::ShaderDataType::Bool:    return GL_INT;
		}
		MGE_CORE_ASSERT(false, "Unknown shader data type!");
		return 0;
	}
	OpenGLVertexArray::~OpenGLVertexArray() {
		glDeleteVertexArrays(1, &rendererID);
	}

	OpenGLVertexArray::OpenGLVertexArray() {
		glCreateVertexArrays(1, &rendererID);
	}

	void OpenGLVertexArray::Bind() const {
		glBindVertexArray(rendererID);
	}

	void OpenGLVertexArray::Unbind() const {
		glBindVertexArray(0);
	}

	void OpenGLVertexArray::AddVertexBuffer(const std::shared_ptr<VertexBuffer>& vertexBuffer) {
		MGE_CORE_ASSERT(vertexBuffer->GetLayout().GetElements().size(), "Vertex Buffer has no layout!");


		glBindVertexArray(rendererID);
		vertexBuffer->Bind();

		uint32_t ind = 0;
		const auto& lay = vertexBuffer->GetLayout();
		for (const auto& ele : lay) {
			glEnableVertexAttribArray(ind);
			glVertexAttribPointer(ind, ele.GetComponentCount(),
				ShaderDataTypeToGLBaseType(ele.Type), ele.Normalized ? GL_TRUE : GL_FALSE, lay.GetStride(), (const void*)ele.Offset);
			ind++;
		}
		vertexBuffers.push_back(vertexBuffer);
	}

	void OpenGLVertexArray::SetIndexBuffer(const std::shared_ptr<IndexBuffer>& _indexBuffer) {
		glBindVertexArray(rendererID);
		_indexBuffer->Bind();

		indexBuffer = _indexBuffer;
	}

}